import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from './index'
import type {
  ResProvince,
  ResProvinceRelationInfo,
  ReqProvinceRelationInfo,
  ReqBaseInfo,
} from '@/types/fillLink'
import { decode, encode } from 'js-base64'

interface FillLinkState {
  provinceList: ResProvince
  subjectByProvince: Partial<ResProvinceRelationInfo>
  currentSubjectByProvinceParram: Partial<ReqProvinceRelationInfo>
  diagnosisParam: Partial<ReqBaseInfo>
}
let state = {} as any
const idCode = localStorage.getItem('idCode')
if (idCode != undefined && idCode != '') {
  state = { ...JSON.parse(decode(idCode)) }
}
const initialState: FillLinkState = {
  provinceList: [],
  subjectByProvince: {},
  currentSubjectByProvinceParram: {},
  ...state,
}

export const fillLinkSlice = createSlice({
  name: 'fillLink',
  initialState,
  reducers: {
    initProvince: (state, action: PayloadAction<ResProvince>) => {
      state.provinceList = action.payload
    },
    setSubjectByProvince: (state, action: PayloadAction<ResProvinceRelationInfo>) => {
      state.subjectByProvince = action.payload
    },
    setCurrentSubjectByProvinceParram: (state, action: PayloadAction<ReqProvinceRelationInfo>) => {
      state.currentSubjectByProvinceParram = action.payload
    },
    setDiagnosisParam: (state, action: PayloadAction<Partial<ReqBaseInfo>>) => {
      state.diagnosisParam = { ...state.diagnosisParam, ...action.payload }
    },
    setLocalstorage: (state) => {
      localStorage.setItem('idCode', encode(JSON.stringify(state)))
    },
  },
})

export const {
  initProvince,
  setSubjectByProvince,
  setCurrentSubjectByProvinceParram,
  setDiagnosisParam,
  setLocalstorage,
} = fillLinkSlice.actions

export const provinceList = (state: RootState) => state.fillLink.provinceList
export const subjectByProvince = (state: RootState) => state.fillLink.subjectByProvince
export const diagnosisParam = (state: RootState) => state.fillLink.diagnosisParam
export const currentSubjectByProvinceParram = (state: RootState) =>
  state.fillLink.currentSubjectByProvinceParram

export default fillLinkSlice.reducer
